$('#soServiceType').css('width', (window.screen.width * 0.9) + 'px');

/**
 * 验证手机号码是否正确，正确返回true
 * @param phoneNumber
 */
function phoneNumberIsRight(phoneNumber) {
    var reg = /^0?1[1-9][0-9]\d{8}$/;
    if (reg.test(phoneNumber)) {
        return true;
    }
    return false;
}

var map, geolocation, mapMarker, clickLng, clickLat, placeSearch, cityArea, lastCity, rem = 0, isClickMap = false,
    isSetTipWidth = false, checkForm = false;
$(function () {
    initMobiscrollDateTime();
    setFormData();
    setServiceDate();
    $('.icon-back').click(function () {
        $('#amapLayerCenter').hide();
    });
    I('soPhone').value = sessionStorage.getItem(SCS_USER_PHONE), btnIssue = $('.btn-issue-service');
    queryAllServiceType();
    //显示高德地图
    showAMap();
    $('#soAddress').focus(function () {
        //如果是FORM表单验证失败获取的焦点则不显示地图
        if (checkForm) {
            checkForm = false;
            return;
        }
        //默认直接定位到上次发布的地址
        lastCity = getLastCity();
        if (lastCity != null && !isNull(lastCity.lng) && !isNull(lastCity.lat)) {
            I("tipInput").value = localStorage.getItem('lastIssueAddress');
            clickLng = lastCity.lng;
            clickLat = lastCity.lat;
            addMapMarker(clickLng, clickLat);
            map.setZoomAndCenter(14, [clickLng, clickLat]);
        }
        $('#amapLayerCenter').show();
        //如果是第一次设置宽度
        if (!isSetTipWidth) {
            setTipInputWidth();
        }
        isSetTipWidth = true;
    });
    $('#btnSureAddress').click(function () {
        sureServiceAddress();//处理服务地址
    });
    //发布服务
    btnIssue.click(function () {
        $(this).attr('disabled', true);
        $(this).text('发布中...');
        issueService();
    });
    $('#tipInput').focus(function () {
        showHistoryAddress(this);
    }).keyup(function () {
        showHistoryAddress(this);
    });
    $('.order-div input').keyup(function () {
        if (!isNull(this.value)) {
            $('#' + this.id + 'Msg').text('');
        }
    });
});

/**
 * 显示历史记录
 * @param ti
 */
function showHistoryAddress(ti) {
    var historyAddress = localStorage.getItem('MAP_ADDRESS'), sahDiv = $('#searchAddressHistory');
    if (!isNull($(ti).val()) || isNull(historyAddress)) {
        sahDiv.hide();
        return;
    }
    historyAddress = JSON.parse(historyAddress);
    var sahLi = $('#searchAddressHistory ul');
    sahLi.empty();
    for (var g = 0; g < historyAddress.length; g++) {
        var ha = historyAddress[g];
        sahLi.append('<li onclick="getAddressByHis(this,' + ha.lng + ',' + ha.lat + ')">' + ha.address + '</li>');
    }
    sahDiv.show();
    $('.amap-sug-result').hide();
}

/**
 * 从历史记录中获取地址信息
 */
function getAddressByHis(ahLi, liLng, liLat) {
    clickLng = liLng;
    clickLat = liLat;
    $('#soAddress').val(ahLi.innerText);
    $('#amapLayerCenter').hide();
}

//查询所有服务类型
function queryAllServiceType() {
    var sTypeArray = getDictionaries('1');
    if (isNull(sTypeArray)) {
        return;
    }
    //添加服务类型列表
    for (var j = 0; j < sTypeArray.length; j++) {
        var st = sTypeArray[j];
        $('#soServiceType').append('<option value="' + st.id + '">' + st.dicName + '</option>');
    }
}

//显示遮罩层和地图
function showAMap() {
    //加载地图，调用浏览器定位服务
    map = new AMap.Map('aMapContainer', {
        resizeEnable: true,
        zoom: 11
    });
    //显示比例尺
    var aMapScale = new AMap.Scale({
        visible: true
    });
    aMapScale.show();
    map.addControl(aMapScale);
    lastCity = getLastCity();
    //如果没有上次城市信息，则重新定位
    if (lastCity == null) {
        map.plugin('AMap.Geolocation', function () {
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 20000,          //超过20秒后停止定位，默认：无穷大
                maximumAge: 3000,           //定位结果缓存0毫秒，默认：0
                showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
                buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                buttonPosition: 'RB'
            });
            map.addControl(geolocation);
            geolocation.getCurrentPosition();
            AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
            AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
        });
    } else {
        currentCityName = lastCity.name;
        currentCityCode = lastCity.code;
        if (isNull(lastCity.lng) || isNull(lastCity.lat)) {
            map.setCity(currentCityName);
        } else {
            clickLng = lastCity.lng;
            clickLat = lastCity.lat;
            addMapMarker(clickLng, clickLat);
            map.setZoomAndCenter(14, [clickLng, clickLat]);
            regeocoder();
        }
        $('#mMyCity').text(currentCityName);
        I('mMyCity').href = 'mCityList.html?cityCode=' + currentCityCode + '&backUrl=mIssueService';
    }

    //为地图注册click事件获取鼠标点击出的经纬度坐标
    map.on('click', function (e) {
        isClickMap = true;
        clickLng = e.lnglat.getLng();
        clickLat = e.lnglat.getLat();
        if (mapMarker != null) {
            map.remove(mapMarker);//清除原来的标记
        }
        //给点击的地方添加标记
        addMapMarker(clickLng, clickLat);
        //给点标记添加移动结束时监听事件
        AMap.event.addListener(mapMarker, 'dragend', mapMarkerDrag);
        regeocoder();
    });
    //输入提示
    var autoOptions = {input: "tipInput"};
    var auto = new AMap.Autocomplete(autoOptions);
    placeSearch = new AMap.PlaceSearch({map: map});  //构造地点查询类
    AMap.event.addListener(auto, "select", select);//注册监听，当选中某条记录时会触发
}

//解析定位结果
function onComplete(data) {
    clickLng = data.position.getLng();
    clickLat = data.position.getLat();
    addMapMarker(clickLng, clickLat);
    map.setZoomAndCenter(14, [clickLng, clickLat]);
    regeocoder();
}

//如果解析精确定位错误，则根据定位的城市名来定位
function onError(data) {
    showCityInfo();
}

//根据IP定位当前城市
function showCityInfo() {
    //实例化城市查询类
    var citysearch = new AMap.CitySearch();
    //自动获取用户IP，返回当前城市
    citysearch.getLocalCity(function (status, result) {
        var isOk = status === 'complete' && result.info === 'OK' && result && result.city && result.bounds;
        if (!isOk) {
            return;
        }
        currentCityName = result.city;
        var nameLen = currentCityName.length;
        var delShiName = currentCityName.substr(nameLen - 1, nameLen);
        if (delShiName == '市') {
            delShiName = currentCityName.substr(0, nameLen - 1);
        }
        last_city_name = localStorage.getItem(LAST_CITY_NAME_KEY);
        if (last_city_name == currentCityName || delShiName == last_city_name) {
            currentCityCode = localStorage.getItem(LAST_CITY_ID_KEY);
        }
    });
}

//当选中某条记录时会触发
function select(e) {
    var eAddress = e.poi.district;
    var eCity = eAddress.split('市')[0];
    if (eCity.indexOf('省') > 0) {
        eCity = eCity.split('省')[1];
    }
    cityArea = eAddress.replace(eCity, '');
    if (isNull(currentCityName)) {
        currentCityName = localStorage.getItem(LAST_CITY_NAME_KEY);
    }
    if (isNull(currentCityName)) {
        //重新定位城市名
        var citysearch = new AMap.CitySearch();
        //自动获取用户IP，返回当前城市
        citysearch.getLocalCity(function (status, result) {
            if (status === 'complete' && result.info === 'OK' && result && result.city && result.bounds) {
                currentCityName = result.city;
                currentCityCode = getCityIdByName(currentCityName);
            }
        });
    }
    //判断当前浏览器定位的城市跟订单地址是否一致，不一致，则提示是否切换
    if (currentCityName != eCity) {
        if (confirm('您发布的服务的城市是<' + eCity + '>，是否切换到该城市？')) {
            currentCityName = eCity;
            getCityIdByName(currentCityName);
        }
    }
    placeSearch.setCity(e.poi.adcode);
    placeSearch.search(e.poi.name);  //关键字查询查询
    clickLng = e.poi.location.lng;
    clickLat = e.poi.location.lat;
    addMapMarker(clickLng, clickLat);
    regeocoder(e.poi.name);
}

//点标记添加移动结束时监听事件函数
function mapMarkerDrag(e) {
    clickLng = e.lnglat.lng;
    clickLat = e.lnglat.lat;
}

//通过经纬度添加地图标记
function addMapMarker(lng, lat) {
    mapMarker = new AMap.Marker({
        map: map,
        icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png",
        draggable: true,  //是否可拖动
        position: [lng, lat]
    });
}

//逆地理编码,经纬度转地址
function regeocoder(e_poi_name) {
    var lnglatXY = [clickLng, clickLat];
    var geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: "all"
    });
    geocoder.getAddress(lnglatXY, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
            geocoderCallBack(result, e_poi_name);
        }
    });
}

//逆地理编码成功后的回调函数
function geocoderCallBack(data, e_poi_name) {
    var address = data.regeocode.formattedAddress; //返回地址描述
    if (isNull(currentCityName)) {
        currentCityName = data.regeocode.addressComponent.province;//设置当前默认城市名
    }
    if (isNull(cityArea)) {
        cityArea = data.regeocode.addressComponent.district;//设置当前默认区县名
    }
    I("tipInput").value = address;
    localStorage.setItem('lastIssueAddress', address);
}

//处理服务订单地址
function sureServiceAddress() {
    //如果没点击地图并地址为空
    if (!isClickMap && isNull(V('tipInput'))) {
        return;
    }
    var mapAddress = V("tipInput");
    if (isNull(clickLat) || isNull(clickLng) || isNull(mapAddress)) {
        $('#soAddressMsg').text('获取精确地址失败，请重新输入地址或点击地图上的地址！');
        return;
    }
    $('#amapLayerCenter').hide();
    I('soAddress').value = mapAddress;
    I('soAddress').blur();
    var mapObj = {
        'lat': clickLat,
        'lng': clickLng,
        'address': mapAddress
    };
    var mapAddressJson = localStorage.getItem('MAP_ADDRESS'), mapArray = new Array();
    if (isNull(mapAddressJson)) {
        mapArray.push(mapObj);
    } else {
        mapArray = JSON.parse(mapAddressJson);
        var isHave = false;
        for (var g = 0; g < mapArray.length; g++) {
            if (mapArray[g].address == mapAddress) {
                isHave = true;
            }
        }
        //如果localStorage中没有该地址信息
        if (!isHave) {
            mapArray.unshift(mapObj);
        }
    }
    $('#soAddressMsg').text('');
    localStorage.setItem('MAP_ADDRESS', JSON.stringify(mapArray));
}

//发布服务
function issueService() {
    if (!checkServiceForm()) {
        setBtnIssue();
        return;
    }
    var userName = sessionStorage.getItem(SCS_USER_NAME), numPrefix = Math.floor(Math.random() * 10) % 3;
    numPrefix += 2;
    if (isNull(userName)) {
        loginConfirm();
        setBtnIssue();
        return;
    }
    if (isNull(cityArea)) {
        cityArea = currentCityName + '周边';
    }
    var formData = getFormData();
    formData['serviceDate'] = V('serviceDate') + ':00';
    formData['soBillNumber'] = numPrefix;
    $.ajax({
        type: 'post',
        url: '/serviceOrder/saveServiceOrder',
        dataType: 'json',
        timeout: 120000,
        data: formData,
        success: function (result) {
            if (result.status == -1) {
                loginConfirm();
                setBtnIssue();
                return;
            }
            if (result.success) {
                setErrorMsg('发布成功');
                addLastCityAddress();
                $('.order-div input,.order-div textarea').val('');
                setBtnIssue();
                $('.pay-method').val('0');
                setServiceDate();
                setTimeout(function () {
                    setErrorMsg('');
                }, 5000);
                sessionStorage.removeItem('lastForm');
                return;
            }
            var errorStr = '当前系统繁忙，请稍候再试', ef = result.errorFlag;
            if (ef == '2') {
                errorStr = '[' + V('serviceDate') + ']不是正确的日期格式';
            } else if (ef == '3') {
                errorStr = '未获取到城市编码';
            }
            setErrorMsg(errorStr);
            setBtnIssue();
        },
        error: function () {
            setErrorMsg("下单失败，请稍候再试");
            setBtnIssue();
        }
    });
}

function setBtnIssue() {
    $('.btn-issue-service').attr({'disabled': false}).text('发布服务');
}

function setErrorMsg(errorStr) {
    $('#lglErrorMsg').text(errorStr);
}

/**
 * 检查表单必填项
 */
function checkServiceForm() {
    var isPass = true;
    $('.order-div input').each(function () {
        var v = this.value, m = $('#' + this.id + 'Msg');
        if (isNull(v)) {
            isPass = false;
            m.text(this.placeholder + '不能为空');
            return false;
        }
    });
    if (isPass && !phoneNumberIsRight(V('soPhone'))) {
        isPass = false;
        $('#soPhoneMsg').text('电话号码不正确');
        return false;
    }
    var amountReg = /^\+?[1-9][0-9]{1,4}(.[0-9]{1,2})?$/;
    if (isPass && !amountReg.test(V('soAmount'))) {
        isPass = false;
        $('#soAmountMsg').text('金额必须大于0且小于10万，保留2位小数');
        return false;
    }
    return isPass;
}

//初始化日期控件
function initMobiscrollDateTime() {
    var now = new Date();
    var mEndYear = now.getFullYear();
    //如果当前时间是12月
    if (now.getMonth() > 10) {
        mEndYear += 1;
    }
    var opt = {};
    opt.date = {preset: 'date'};
    //opt.datetime = {preset : 'datetime', minDate: new Date(2012,3,10,9,22), maxDate: new Date(2014,7,30,15,44), stepMinute: 5};
    opt.datetime = {preset: 'datetime'};//datetime
    opt.time = {preset: 'time'};
    opt.default = {
        theme: 'android-ics light', //皮肤样式
        display: 'modal', //显示方式
        mode: 'scroller', //日期选择模式
        lang: 'zh',
        dateFormat: 'yyyy-mm-dd HH:ii',
        minDate: new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes()),
        maxDate: new Date(now.getFullYear(), now.getMonth() + 1, now.getDate(), now.getHours(), now.getMinutes()),
        startYear: now.getFullYear(), //开始年份
        endYear: mEndYear //结束年份
    };
    var optDateTime = $.extend(opt['datetime'], opt['default']);//datetime
    var optTime = $.extend(opt['time'], opt['default']);
    $("#serviceDate").mobiscroll(optDateTime).datetime(optDateTime);
}

function setTipInputWidth() {
    var ti = $("#tipInput");
    var tipInputWidth = ti.width(), remPx = $("html").css('fontSize'), tiMarginTop = ti.css('marginTop');
    ;
    rem = parseInt(remPx.replace('px', ''));
    //2=0.7+1.3:tipInput.padding-left + btnSureAddress.width
    ti.css('width', (tipInputWidth - (rem * 2)) + 'px');
    tiMarginTop = parseInt(tiMarginTop.replace('px', ''));
    $("#searchAddressHistory").css({
        'width': (tipInputWidth - 2 - (rem * 1.3)) + 'px',
        'top': $('.page-top-tip').height() - tiMarginTop
    });
}

/**
 * 获取上次的城市对象
 */
function getLastCity() {
    var lc = localStorage.getItem(LAST_CITY);
    if (isNull(lc)) {
        return null;
    }
    return JSON.parse(lc);
}

function addLastCityAddress() {
    var cityObj = {
        'code': currentCityCode,
        'name': currentCityName,
        'lat': clickLat,
        'lng': clickLng,
        'address': V('soAddress')
    };
    sessionStorage.setItem(LAST_CITY, JSON.stringify(cityObj));
}

/**
 * 登录确认
 */
function loginConfirm() {
    popTipShow.confirm('登录确认', '您需要先登录才能发布', ['去登录', '不去'], function (e) {
        if ($(e.target).attr('class') != 'ok') {
            this.hide();
            return;
        }
        sessionStorage.setItem('lastForm', JSON.stringify(getFormData()));
        sessionStorage.setItem('lastRequestUrl', 'mIssueService.html');
        window.location.href = 'mUserLogin.html';
    });
}

/**
 * 将上次填写没保存的数据重新填充
 */
function setFormData() {
    var lastForm = sessionStorage.getItem('lastForm');
    if (isNull(lastForm)) {
        return;
    }
    var formObj = JSON.parse(lastForm);
    for (var inputId in formObj) {
        var inputValue = formObj[inputId];
        if (inputId == 'soCityCode') {
            currentCityCode = inputValue;
        } else if (inputId == 'cityName') {
            currentCityName = inputValue;
        } else if (inputId == 'cityArea') {
            cityArea = inputValue;
        } else if (inputId == 'soLng') {
            clickLng = inputValue;
        } else if (inputId == 'soLat') {
            clickLat = inputValue;
        } else if (inputId == 'soPaymentMenthod') {
            $('.pay-method').each(function () {
                if (this.value == inputValue) {
                    $(this).attr('checked', 'checked');
                }
            });
        } else {
            $('#' + inputId).val(inputValue);
        }
    }
}

function setServiceDate() {
    var now = new Date();
    var nowStr = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes();
    $("#serviceDate").val(nowStr);
}

//获取表单数据
function getFormData() {
    return {
        'soName': V('soName'), 'serviceDate': V('serviceDate'),
        'soServiceType': V('soServiceType'), 'soCityCode': currentCityCode,
        'cityName': currentCityName, 'cityArea': cityArea,
        'soAddress': V('soAddress'), 'soPhone': V('soPhone'), 'soAmount': V('soAmount'), 'soDesc': V('soDesc'),
        'soPaymentMenthod': $('input[name="soPaymentMethod"]:checked').val(), 'soLng': clickLng, 'soLat': clickLat
    };
}